<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="socket.io.js"></script>
    <style>
        .mine{ background: gray;}
    </style>
    <script>
        let sock = io.connect("ws://localhost:8086/")

        window.onload = function(){  
            let cur_username = "";   
            let oBtn1 = document.getElementById("btn1");
            let oBtn2 = document.getElementById("btn2");
            let oUser = document.getElementById("user");
            let oPass = document.getElementById("pass");
            let oSend = document.getElementById("send");
            let oTxt = document.getElementById("txt1");
            let oUl = document.getElementById("ul1");

            // on方法放在click事件外面，可以防止多次触发的问题。
            sock.on("reg_ret", (code, msg) => {
                if(code) {
                    alert(msg)
                } else {
                    alert("注册成功")
                }
            })

            sock.on("login_ret", (code, msg) => {
                if(code) {
                    alert(msg)
                } else {
                    cur_username = oUser.value
                    alert("登录成功")
                }
            })

            sock.on("msg_reg", (code, msg) => {
                if(code) {
                    alert(msg)
                } else {
                    let oLi = document.createElement("li");
                    oLi.className = "mine";
                    oLi.innerHTML = `<h4>${cur_username}</h4><p>${oTxt.value}</p>`;              
                    oUl.appendChild(oLi);
                    oTxt.value = "";
                }
            })

            sock.on("msg", (name, txt) => {
                let oLi = document.createElement("li");
                oLi.innerHTML = `<h4>${name}</h4><p>${txt}</p>`;              
                oUl.appendChild(oLi);
            })

            oBtn1.onclick = function() {
                sock.emit("reg", oUser.value, oPass.value)               
            }
            oBtn2.onclick = function() {
                sock.emit("login", oUser.value, oPass.value)               
            }
            oSend.onclick = function() {
                sock.emit("msg", oTxt.value)
            }
        }
    </script>
</head>
<body>
    user: <input type="text" id="user"/>
    password: <input type="password" id="pass"/>
    <input type="button" value="提交" id="btn1"/>
    <input type="button" value="登录" id="btn2"/>
    <br />
    <br />
    <br />
    <textarea id="txt1" rows="4" cols="80"></textarea><br />
    <input type="button" value="send" id="send">

    <ul id="ul1">

    </ul>
</body>
</html>